<template>
  <a-modal
    v-model:visible="visible"
    title="修改密码"
    wrapClassName="custom-modal min-base-modal"
    @cancel="handleCancel"
    :maskClosable="false"
    :destroyOnClose="true"
    width="28rem"
  >
    <a-form
      ref="formRef"
      :rules="rules"
      :model="formState"
      name="platform-config"
      class="password-form"
    >
      <a-form-item
        :label-col="{ span: 6 }"
        label="原密码"
        name="oldPassWord"
        required
      >
        <a-input
          v-model:value="formState.oldPassWord"
          placeholder="请输入原密码"
          type="password"
        />
      </a-form-item>
      <a-form-item :label-col="{ span: 6 }" label="新密码" name="newPassWord">
        <a-input
          type="password"
          v-model:value="formState.newPassWord"
          placeholder="请输入新密码"
        />
      </a-form-item>
      <a-form-item
        :label-col="{ span: 6 }"
        label="密码确认"
        name="confirmPassWord"
      >
        <a-input
          type="password"
          v-model:value="formState.confirmPassWord"
          placeholder="请确认密码"
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button key="back" type="cancel" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="submit" :loading="loading" @click="handleOk">
        确定
      </a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { validatePasswordStrength } from '@/utils/validate'
import type { RuleObject, Rule } from 'ant-design-vue/es/form'
import { useInfoStore } from '@/store'
import { changePwd } from '@/api/user'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { sm2Encryption } from '@/utils/common'
const router = useRouter()
// 个人信息
const userStore = useInfoStore()

const visible = ref<boolean>(false)
const loading = ref<boolean>(false)
const formRef = ref()
const handleCancel = () => {
  visible.value = false
}

const handleOk = async () => {
  try {
    await formRef.value.validateFields()
    loading.value = true
    const newPwd = sm2Encryption(formState.newPassWord)
    const username = userStore.userName
    const data = {
      newPassWord: newPwd,
      confirmPassWord: newPwd,
      oldPassWord: sm2Encryption(formState.oldPassWord),
      username
    }
    changePwd(data)
      .then((res) => {
        loading.value = false
        message.success('修改密码成功，请重新登录！')
        router.push('/login')
      })
      .catch(() => {
        loading.value = false
      })
  } catch (errorInfo) {
    console.log('Failed:', errorInfo)
  }
}

const showModal = () => {
  visible.value = true
  formState.newPassWord = ''
  formState.oldPassWord = ''
  formState.confirmPassWord = ''
}

const formState = reactive({
  confirmPassWord: '',
  oldPassWord: '',
  newPassWord: ''
})

const validatePwd = (rule: RuleObject, value: string) => {
  return validatePasswordStrength(rule, value)
}
const validatePass2 = async (rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject(new Error('请确认密码'))
  } else if (value !== formState.newPassWord) {
    return Promise.reject(new Error('两次密码不匹配！'))
  } else {
    return Promise.resolve()
  }
}

const rules: Record<string, Rule[]> = {
  oldPassWord: [{ required: true, trigger: 'blur' }],
  newPassWord: [{ required: true, validator: validatePwd, trigger: 'blur' }],
  confirmPassWord: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
}

defineExpose({ showModal })
</script>
<style lang="less">
.password-form {
  .ant-form-item-label > label::after {
    content: '';
  }

  .ant-row {
    display: block;
  }

  .ant-form-item-label {
    text-align: left;
  }
}
</style>
